package com.zjl.zweather.logic.network

import com.zjl.zweather.logic.network.ServiceCreator.create
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.await
import java.lang.RuntimeException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * Created by admin on 2020/12/1 .
 * With com.zjl.zweather.logic.network
 */
/**
 * Created by admin on 2020/12/1 .
 * With com.zjl.zweather.logic.network
 *
 * 统一的网络数据源访问入口
 */
object ZWeatherNetWork {

    private val placeService = ServiceCreator.create<PlaceService>()

    /**
     * 请求搜索城市数据
     *
     */
    suspend fun searchPlaces(query: String) = placeService.searchPlaces(query).await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }

                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) {
                        continuation.resume(body)
                    } else {
                        continuation.resumeWithException(RuntimeException("response body is null"))
                    }
                }

            })
        }
    }

}